package com.wx;


import java.io.*;
import java.net.*;
import java.time.LocalDate;

public class ServerThread extends Thread {
    Socket socket = null; //保存与本线程相关的Socket对象
    //	private BufferedReader br;
    private DataInputStream dis;

    int clientnum; //保存本进程的客户计数

    public ServerThread(Socket socket, int num) { //构造函数
        this.socket = socket; //初始化socket变量
        clientnum = num + 1; //初始化clientnum变量
        try {
            dis = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                String msg = dis.readUTF(); //br.readLine();
                System.out.println(msg);
                String[] str = msg.split(",");
                if (str.length > 1) {
                    MultiTalkServer.userSocket.put(str[1], socket);
                }
                switch (str[0]) {
                    case "msg":
                        sendToClient(str[1], str[2], str[3]); // 转发信息给特定的用户
                        break;
                    case "file":
                        String fileMsg = msg;
                        long fileSize = dis.readLong();
                        System.out.println("文件大小:" + fileSize);
                        byte[] buf = new byte[Integer.valueOf(fileSize + "")];
                        int len = 0;
                        String fileName = fileMsg.split(",")[3];
                        String newFilePath = fileMsg.split(",")[4];
                        newFilePath = getServerFilePath(newFilePath);
                        System.out.println(newFilePath);
                        File file = new File(newFilePath);
                        DataOutputStream dos = new DataOutputStream(
                                new FileOutputStream(file));
                        while ((len = dis.read(buf)) != -1) {
                            dos.write(buf, 0, len);
                            if (file.length() >= fileSize) {
                                break;
                            }

                        }
                        dos.flush();
                        dos.close();
                        sendFileToClient(str[1], str[2], newFilePath, fileSize);
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            System.out.println("异常");
        } finally {
            try {
                this.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 构建服务器文件存储路径
     *
     * @param newFilePath
     * @return
     */
    private String getServerFilePath(String newFilePath) {
        String fileSep = File.separator;
        int index = newFilePath.lastIndexOf(fileSep);
        String newPath = newFilePath.substring(0, index);
        newPath = newPath + fileSep + "serve" + LocalDate.now().toString() + fileSep + newFilePath.substring(index + 1);
        File file = new File(newPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return newPath;
    }

    /***
     * 将toSendFilePath文件发给to
     * @param from
     * @param to
     * @param toSendFilePath
     */
    private void sendFileToClient(String from, String to, String toSendFilePath, long fileSize) {
        File sendFile = new File(toSendFilePath);
        Socket userSocket = MultiTalkServer.userSocket.get(to);
        String msg = "$file$[from " + from + "]" + "," + sendFile.length() + "," + sendFile.getName();
        if (userSocket != null) {
            try {
                DataOutputStream out = new DataOutputStream(userSocket.getOutputStream());
                out.writeUTF(msg);
                out.flush();
                //发送文件给to
                DataInputStream dis = new DataInputStream(new FileInputStream(toSendFilePath));
                byte[] buf = new byte[Integer.valueOf(sendFile.length() + "")];
                int len = 0;
                while ((len = dis.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
                out.flush();
                dis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void sendToClient(String from, String to, String msg) {
        Socket userSocket = MultiTalkServer.userSocket.get(to);
        msg = "[from " + from + "] " + msg;
        if (userSocket != null) {
            try {
                //PrintWriter pw = new PrintWriter(userSocket.getOutputStream());
                DataOutputStream out = new DataOutputStream(userSocket.getOutputStream());
                out.writeUTF(msg);
                out.flush();
                //pw.println(msg);
                //pw.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
